<template>
  <div class="container">
    <div class="content">
      <div class="left">

        <div class="con-box info">
          <div class="title">
            叫号总览
          </div>
          <div class="main">
            <div class="item">
              <div class="label">已叫:</div>
              <div class="value">{{ callWorkData.deliveredCount }}</div>
            </div>
            <div class="item">
              <div class="label">等待:</div>
              <div class="value">{{ callWorkData.waitCount }}</div>
            </div>
            <div class="item">
              <div class="label">过号:</div>
              <div class="value">{{ callWorkData.passCount }}</div>
            </div>
          </div>
        </div>

        <div class="con-box user">
          <div class="control">
            <div class="title-avatar">
              <div class="title">公证员</div>
              <div class="avatar">
                <img :src="userInfo.coverUrl" alt="" />
              </div>
            </div>
            <div class="exit" @click="isShow = true;">
              <img class="icon" src="../assets/exit.svg" alt="">
            </div>
          </div>
          <div class="main">
            <div class="item">
              <div class="label">姓名:</div>
              <div class="value">{{ userInfo.name }}</div>
            </div>
            <div class="item">
              <div class="label">科室:</div>
              <div class="value">{{ userInfo.windowsName }}</div>
            </div>
            <div class="item">
              <div class="label">业务:</div>
              <div class="value">{{userInfo.typeName}}</div>
            </div>
          </div>
        </div>

      </div>
      <div class="right">
        <div class="call-number-status">
          <div v-if="!callNumberStatus" class="start" @click="handleStart">
            开始叫号
          </div>

          <div v-else class="afoot">

            <div class="call-box">
              <div class="label">当前叫号</div>
              <div class="value">{{ callWorkData.nowCallUserResult?.reservationNum }}</div>
            </div>

            <template v-if="!isReach">
              <div class="call-btn success" @click="handleReach">到场</div>
              <div class="call-btn wraing" @click="getNowAudio(1)">重呼</div>
              <div class="call-btn error" @click="getNowAudio(2)">过号</div>
            </template>

            <template v-else>
              <div class="call-btn success max" @click="handleNext">下一位</div>
            </template>



            <div class="call-btn error" @click="handleEnd">暂停叫号</div>
          </div>
        </div>
      </div>
    </div>
    <Dialog :show="isShow" @confirm="handleConfirm" @cancel="handleCancel"></Dialog>
    <Dialog :show="isShowCall" title="当前号码尚未播报，是否继续？" @confirm="handleConfirmByCall" @cancel="handleCancelByCall"></Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { resetRouter } from '@renderer/router/index';
import Dialog from "@renderer/components/dialog/index.vue";
import { quit } from '@renderer/api/auth/index';
import { callWork, call, arrival, end, pass, againCall,nowAudio } from '@renderer/api/home/index';
import {useUserStore} from '@renderer/store/modules/user';
import { callWorkResult } from '@renderer/api/home/types';
import { ElLoading } from 'element-plus';

const callNumberStatus = ref(false);
const isReach = ref(false);
const isShow = ref(false);
const isShowCall = ref(true);
const clearTime = ref();
const currentType = ref(0)
const callWorkData = ref<callWorkResult>({
  deliveredCount: 0,
  passCount: 0,
  waitCount: 0,
  nowCallUserResult: null
});
const userInfo = ref({
  name: '',
  windowsName: '',
  coverUrl: '',
  typeName: ''
});



onMounted(() => {
  getCallWork();
  getUserStore();
  clearTime.value = setInterval(() => {
    getCallWork();
  }, 5000);
});

onBeforeUnmount(() => {
  clearInterval(clearTime.value);
});
// 开始叫号
function handleStart() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  call().then(async res => {
    console.log('res', res);
    await getCallWork();
    callNumberStatus.value = true;
    loading.close();
  }).catch(() => {
    loading.close();
  });

}

// 下一位
function handleNext() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  call().then(async () => {
    isReach.value = false;
    await getCallWork();
    loading.close();
  }).catch(async () => {
    await getCallWork();
    loading.close();
  });
}

// 到场
function handleReach() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  arrival({ recordId: callWorkData.value.nowCallUserResult?.recordId }).then(res => {
    console.log('res', res);
    isReach.value = true;
    loading.close();
  }).catch(() => {
    loading.close();
  });
}

// 确定退出
function handleConfirm() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  quit({
    imei: 'a345321c-2880-4174-a5e0-7cd2a1102899'
  }).then(() => {
    clearInterval(clearTime.value);
    resetRouter();
    localStorage.removeItem('token');
    loading.close();
  }).catch(() => {
    loading.close();
  });

}

function handleCancel() {
  isShow.value = false;
}


// 确定操作
function handleConfirmByCall () {
    isShowCall.value = false;
    if(currentType.value == 1) {
      handleAgainCall()
    } else if(currentType.value == 2) {
      handlePass()
    }
}

function handleCancelByCall () {
  isShowCall.value = false;
}
// 叫号
function getCallWork() {
  return new Promise<void>((resolve, rejects) => {
    callWork().then((res) => {
      console.log(res);
      callWorkData.value = res.data;
      resolve();
      if (res.data.nowCallUserResult == null) {
        callNumberStatus.value = false;
      } else {
        callNumberStatus.value = true;

        // windowsStatus 为 0 无排队
        if (res.data.windowsStatus === 0) {
          callNumberStatus.value = false;
          isReach.value = false;
        }
        // status 为 4，已到场
        if (res.data.nowCallUserResult.recordStatus == 4) {
          isReach.value = true;
        } else {
          isReach.value = false;
        }
      }
    }).catch(() => {
      rejects();
    });
  });
}

// 暂停叫号
function handleEnd() {

  end({ recordId: callWorkData.value.nowCallUserResult?.recordId }).then(res => {
    console.log('res', res);
    callNumberStatus.value = false;
  });
}
// 过号
function handlePass(): void {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  if (!callWorkData.value.nowCallUserResult?.recordId) {
    return;
  }

  pass({ recordId: callWorkData.value.nowCallUserResult?.recordId }).then(async res => {
    console.log('res', res);
    await getCallWork();
    loading.close();
  }).catch(() => {
    callNumberStatus.value = false;
    loading.close();
  });

}

// 重新呼叫
function handleAgainCall() {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  againCall().then(res => {
    console.log('againCall',res);
    loading.close();
  }).catch(() => {
    loading.close();
  });
}

function getUserStore() {
  const userstore = useUserStore();
  const user = userstore.getUser();
  if(user) {
    userInfo.value = JSON.parse(user)
  }
  console.log(userInfo.value.name);
  
}

function getNowAudio(type: number) {
  currentType.value = type;

  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  nowAudio({id: callWorkData.value.nowCallUserResult?.recordId}).then(res => {
    console.log('res', res);
    loading.close();
    if(res.data == 0) {
      isShowCall.value = true;
      
    }else {
      if(type == 1) {
        handleAgainCall()
      } else if(type == 2) {
        handlePass()
      }
    }
    
  }
  )
}



</script>

<style scoped lang="scss">
.container {
  height: 100vh;
  width: 100%;


  .content {
    display: flex;

    .con-box {
      width: 300px;
      height: auto;
      background-color: #ffffff;
      padding: 45px 40px;
      border: 1px solid rgb(187, 187, 187);
      border-radius: 12px;

      .title {
        font-size: 22px;
        font-weight: bold;
        margin-bottom: 30px;
      }

      .control {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 30px;

        .title-avatar {
          display: flex;
          align-items: center;

          .title {
            margin-bottom: 0;
          }

          .avatar {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            margin-left: 8px;
            img {
              width: 30px;
            height: 30px;
                        border-radius: 50%;
            }
          }
        }

        .exit {
          cursor: pointer;
          display: flex;
          align-items: center;

          .icon {
            width: 20px;

          }
        }

      }

      .main {
        .item {
          font-size: 18px;

          display: flex;

          .value {
            margin-left: 10px;
          }

          .label,
          .value {
            font-weight: 400;
          }
        }

        .item+.item {
          margin-top: 10px;
        }

      }

    }



    .right {
      margin-left: 30px;
    }
    .left {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
  }

  .call-number-status {
    width: 300px;
    height: 535px;

    .start {
      width: 300px;
      height: 535px;
      background-color: rgb(32, 100, 240);
      border-radius: 12px;
      color: #ffffff;
      font-size: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
  }

  .call-box {
    width: 100%;
    height: 100px;
    border: 1px solid rgb(187, 187, 187);
    border-radius: 12px;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 50px;

    .label,
    .value {
      font-size: 22px;
      font-weight: bold;
    }

    .value {
      color: rgb(32, 100, 240);
    }
  }

  .afoot {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .call-btn {
    width: 100%;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
    font-weight: bold;
    color: #ffffff;

    border-radius: 12px;
    cursor: pointer;

  }

  .success {
    height: 120px;
    background-color: rgb(32, 100, 240);
  }

  .success.max {
    height: 300px;
  }

  .wraing {
    height: 120px;
    background-color: rgb(255, 121, 0);
  }

  .error {
    border: 2px solid rgb(237, 37, 36);
    color: rgb(237, 37, 36);
  }

}
</style>
